package com.hong.chapter10;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * 实现一个显示锁lock
 */
public class TestLock {
    public static void main(String[] args) throws InterruptedException {
        final BooleanLock booleanLock = new BooleanLock();
        Stream.of("T1","T2","T3","T4")
                .forEach(name->{
                    new Thread(()->{
                        try {
                            booleanLock.lock(10l);
                            Optional.of(Thread.currentThread().getName()+" have the lock Monitor")
                                    .ifPresent(System.out::println);
                            work();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (LOCK.TimeOutException e) {
                            Optional.of(Thread.currentThread().getName()+"time out")
                                    .ifPresent(System.out::println);
                            e.printStackTrace();
                        } finally {
                            booleanLock.unlock();
                        }
                    },name).start();
                });

        Thread.sleep(10);
        booleanLock.unlock();
    }

    public  static void work() throws InterruptedException {
        Optional.of(Thread.currentThread().getName()+"is Working...")
                .ifPresent(System.out::println);
        Thread.sleep(40_000);
    }
}
